package com.py.custom.common.web.log;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.Objects;

/**
 * description：ApplicationEnvironmentPreparedEvent - 应用环境准备事件
 *
 * @author pengyou
 * @version 1.0.0
 * @date 2021/10/17
 */
public class LogMDCListener implements GenericApplicationListener {

    private static final String APPLICATION_CONFIG_NAME = "configurationProperties";

    private static final String APP_NAME = "spring.application.name";

    private static final String LOG_NAME = "logging.file.name";

    private static final String LOG_PATH = "logging.file.path";


    /**
     * 监听指定类型的事件，返回true，就执行onApplicationEvent方法
     *
     * @param resolvableType
     * @return
     */
    @Override
    public boolean supportsEventType(ResolvableType resolvableType) {
        Class<?> rawClass = resolvableType.getRawClass();
        if (Objects.isNull(rawClass)) {
            return false;
        }
        return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(rawClass);
    }

    /**
     * 通过应用环境，获取配置信息
     *
     * @param applicationEvent
     */
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        ApplicationEnvironmentPreparedEvent environmentPreparedEvent = (ApplicationEnvironmentPreparedEvent) applicationEvent;
        ConfigurableEnvironment environment = environmentPreparedEvent.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        PropertySource<?> propertySource = propertySources.get(APPLICATION_CONFIG_NAME);
        // 空值判断
        assert propertySource != null;
        String logName = (String) propertySource.getProperty(LOG_NAME);
        String logPath = (String) propertySource.getProperty(LOG_PATH);
        MDC.put("logName", logName);
        MDC.put("logPath", logPath);
    }

    /**
     * 调用时机；优先级
     *
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }

}
